package xcmg.syn.util;

import org.scribe.exceptions.OAuthSignatureException;
import org.scribe.services.Base64Encoder;
import org.scribe.services.SignatureService;
import org.scribe.utils.OAuthEncoder;
import org.scribe.utils.Preconditions;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author senlin.yang@hand-china.com
 * @version V1.0
 * @Date 2020-12-1
 * @description Hmac-sha256签名方式
 */
public class HMACSha256SignatureService implements SignatureService {

    private static final String UTF8 = "UTF-8";
    private static final String HMAC_SHA256 = "HmacSHA256";
    private static final String METHOD = "HMAC-SHA256";

    @Override
    public String getSignature(String baseString, String apiSecret, String tokenSecret) {
        try {
            Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string");
            Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string");

            String keyString = OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret);
            SecretKeySpec key = new SecretKeySpec(keyString.getBytes(UTF8), HMAC_SHA256);

            Mac mac = Mac.getInstance(HMAC_SHA256);
            mac.init(key);
            byte[] data = mac.doFinal(baseString.getBytes(UTF8));

            return this.bytesToBase64String(data);
            // byte[] hex = (new Hex()).encode(data);
            // return (new String(hex, Charset.forName("UTF-8"))).toUpperCase();
        } catch (Exception e) {
            throw new OAuthSignatureException(baseString, e);
        }
    }

    private String bytesToBase64String(byte[] bytes) {
        return Base64Encoder.getInstance().encode(bytes);
    }

    @Override
    public String getSignatureMethod() {
        return METHOD;
    }
}
